package com.soft.line.service.impl;

import com.soft.line.common.AppletSystemConstant;
import com.soft.line.entity.AppletContract;
import com.soft.line.entity.AttachmentInfo;
import com.soft.line.mapper.AppletCommonMapper;
import com.soft.line.mapper.AppletContractMapper;
import com.soft.line.service.AppletContractService;
import com.soft.line.util.MP.AjaxResult;
import com.soft.line.util.exception.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 小程序合同serviceImpl
 *
 * @author wpb
 * @version 1.0
 * @date 2020/5/26 15:47
 */
@Service
@Slf4j
public class AppletContractServiceImpl implements AppletContractService {

    /**
     * 虚拟
     */
    @Value("${uploadFileMapping}")
    private String uploadFileMappingUrl;

    /**
     * 文件上传路径  例如：D盘下的路径
     */
    @Value(value = "${uploadFileDir}")
    private String uploadFileDir;

    @Autowired
    private AppletContractMapper appletContractMapper;

    @Autowired
    private AppletCommonMapper appletCommonMapper;

    @Override
    public AjaxResult getContractNum() {
        Map<String, Long> map = new HashMap<>(0);
        List<Map<String, Long>> mapList = appletContractMapper.contractNum();
        //查询所有部门 code_detail
        List<String> deptIds = appletCommonMapper.codeDetailList(AppletSystemConstant.CODE_TYPE_DEPT);
        if (deptIds.size() > 0) {
            for (String deptId : deptIds) {
                map.put(deptId, 0L);
            }
            for (Map<String, Long> mapData : mapList) {
                for (String deptId : deptIds) {
                    if (deptId.equals(String.valueOf(mapData.get("depId")))) {
                        map.put(deptId, mapData.get("value"));
                    }
                }
            }
        } else {
            return AjaxResult.error("查询部门出错");
        }
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult getContractYearList(Map<String, Object> paraMap) {

        //获取今年字符串 例：2020
        String year = getDate("yyyy", new Date());
        //设置 部门合同年列表初始值

        List<Map<String, Object>> list = new ArrayList<>();

        for (int i = Integer.parseInt(year); i > AppletSystemConstant.ASSIGN_YEAR; i--) {
            Map<String, Object> map = new HashMap<>(0);
            map.put("signTime", String.valueOf(i));
            map.put("num", AppletSystemConstant.NUM);
            list.add(map);
        }

        Map<String, Object> map = new HashMap<>(0);
        map.put("signTime", AppletSystemConstant.NUM);
        map.put("num", AppletSystemConstant.NUM);
        list.add(map);

        //根据部门id获取合同年列表数据
        List<Map<String, Object>> mapLists = appletContractMapper.getContractYearList(paraMap);

        if (mapLists.size() > 0) {
            //2005 年之前的，不包含2005
            int num = 0;
            int time = 2005;
            for (Map<String, Object> mapYear : mapLists) {
                if (Integer.parseInt(mapYear.get("signTime").toString()) < time) {
                    num += Integer.parseInt(mapYear.get("num").toString());
                }
            }

            //数据处理

            for (Map<String, Object> mapList : list) {
                for (Map<String, Object> mapData : mapLists) {
                    if (Integer.parseInt(mapList.get("signTime").toString()) != 0) {
                        if (mapList.get("signTime").equals(mapData.get("signTime"))) {
                            mapList.put("num", mapData.get("num"));
                        }
                    } else {
                        mapList.put("num", num);
                    }
                }
            }
        }

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getContractList(Map<String, Object> paraMap) {
        Map<String, Object> map = new HashMap<>(0);
        //从第几条开始
        int num = ((int) paraMap.get("pageNum") - 1) * ((int) paraMap.get("dataNum"));
        paraMap.put("pageNum", num);

        List<Map<String, Object>> mapList = appletContractMapper.getContractList(paraMap);

        //条件下的总个数
        int i = appletContractMapper.countContractList(paraMap.get("depId").toString(), paraMap.get("signTime").toString());

        //总个数大于  当前数据+10
        map.put("hasMore", i > (num + ((int) paraMap.get(AppletSystemConstant.DATA_NUM))));
        map.put("contractList", mapList);

        return AjaxResult.success(map);
    }


    @Override
    public AjaxResult getContractSearchList(Map<String, Object> paraMap) {
        Map<String, Object> map = new HashMap<>(0);
        //从第几条开始
        int num = ((int) paraMap.get("pageNum") - 1) * ((int) paraMap.get("dataNum"));
        paraMap.put("pageNum", num);

        List<Map<String, Object>> mapList = appletContractMapper.getContractSearchList(paraMap);

        //条件下的总个数
        int i = appletContractMapper.countContractSearchList(paraMap.get("contractName").toString());

        //总个数大于  当前数据+10
        map.put("hasMore", i > (num + ((int) paraMap.get(AppletSystemConstant.DATA_NUM))));
        map.put("contractList", mapList);

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult getContractQueryList(Map<String, Object> paraMap) {
        Map<String, Object> map = new HashMap<>(0);
        //从第几条开始
        int pageNum = ((int) paraMap.get("pageNum") - 1) * ((int) paraMap.get("dataNum"));
        paraMap.put("pageNum", pageNum);
        List<String> idList = new ArrayList<String>();
        List<Map<String, Object>> lists = new ArrayList<>();
        List<Map<String, Object>> mapList = appletContractMapper.getContractQueryList(paraMap);
        if (mapList.size() > 0) {
            for (Map<String, Object> mp : mapList) {
                idList.add(mp.get("id").toString());
            }
            mapList = appletContractMapper.getAboutContractNatureByIdList(paraMap, idList);
            for (Map<String, Object> mp : mapList) {
                idList.add(mp.get("id").toString());
            }
            paraMap.put("idList", idList);
            mapList = appletContractMapper.getAboutAllContractsByIdList(paraMap);
        }
        lists = mapList;
        //条件下的总个数
        int i = lists.size();

        //总个数大于  当前数据+10
        map.put("hasMore", i > (pageNum + ((int) paraMap.get(AppletSystemConstant.DATA_NUM))));
        map.put("contractList", lists);

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult addContract(AppletContract appletContract) {
        if (appletContractMapper.checkContractByName(appletContract.getContractName()) != 0) {
            return AjaxResult.error("合同已存在");
        }

        //默认不删除
        appletContract.setDelFlg("0");
        //日期
        appletContract.setModifyTime(new Date());

        int i = appletContractMapper.addContract(appletContract);
        Map<String, Object> map = new HashMap<>(0);
        if (i == 1) {
            map.put("id", appletContract.getId());
        } else {
            CommonResult.failed("添加合同失败");
        }
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult updateContract(AppletContract appletContract) {
        if (appletContractMapper.checkContractByNameAndId(appletContract.getContractName(), appletContract.getId()) != 0) {
            return AjaxResult.error("合同已存在");
        }

        appletContract.setModifyTime(new Date());
        int count = appletContractMapper.updateContract(appletContract);

        if (count != 1) {
            return AjaxResult.error("修改合同失败");
        }

        List<AttachmentInfo> deleteAttachmentList = appletContract.getDeleteAttachmentList();

        StringBuilder deleteErrorMsg = new StringBuilder();

        if (deleteAttachmentList.size() > 0) {

            //执行删除
            for (AttachmentInfo attachmentInfo : deleteAttachmentList) {
                //附件表 url
                String attachmentUrl = attachmentInfo.getAttachmentUrl();
                String fileUrl = attachmentUrl.substring(attachmentUrl.indexOf(uploadFileMappingUrl) + 12);

                //删除附件文件
                File fileDir = new File(uploadFileDir + fileUrl);
                boolean deleteResult = fileDir.delete();

                if (!deleteResult) {
                    //deleteErrorMsg += "，删除文件：" + attachmentUrl.substring(attachmentUrl.lastIndexOf("/")) + "失败";
                    deleteErrorMsg.append("，删除文件：").append(attachmentUrl.substring(attachmentUrl.lastIndexOf("/") + 1)).append("失败");
                } else {
                    appletCommonMapper.delAnnex(attachmentInfo.getId());
                }

            }
        }

        return AjaxResult.success("修改合同成功" + deleteErrorMsg);
    }

    @Override
    public AjaxResult getContract(Map<String, Object> paraMap) {
        //合同详情
        Map<String, Object> map = appletContractMapper.getContract(paraMap);
        if (map == null || map.isEmpty()) {
            return AjaxResult.error("未查询出结果");
        }

        //如果值为null 转化为""
        for (String key : map.keySet()) {
            if (map.get(key) == null) {
                map.put(key, "");
            }
        }
        map.put("totalAmount", ((BigDecimal) map.get("totalAmount")).stripTrailingZeros().toPlainString());

        //附件详情
        int cId = (int) paraMap.get("id");
        String type = "1";
        List<Map<String, Object>> getAnnexesList = appletCommonMapper.getAnnexes(cId, type);

        List<Map<String, Object>> annexesList = new ArrayList<>();
        // 拼 路径 uploadFileMappingUrl
        for (Map<String, Object> mapAnnex : getAnnexesList) {
            mapAnnex.put("attachmentUrl", uploadFileMappingUrl + mapAnnex.get("attachmentUrl"));
            annexesList.add(mapAnnex);
        }

        map.put("attachmentList", annexesList);
        return AjaxResult.success(map);
    }

    /**
     * 删除合同
     *
     * @param paraMap 参数
     */
    @Override
    public AjaxResult deleteContract(Map<String, Object> paraMap) {
        //删除时间
        paraMap.put("modifyTime", new Date());
        //删除状态
        paraMap.put("delFlg", "1");
        int i = appletContractMapper.deleteContract(paraMap);
        if (i != 1) {
            return AjaxResult.error("删除合同失败");
        } else {
            //附件信息
            List<Map<String, Object>> oldAttachments = appletCommonMapper.getAnnexes((int) paraMap.get("id"), "1");

            //删除附件
            for (Map<String, Object> map : oldAttachments) {
                //附件表 url
                String attachmentUrl = (String) map.get("attachmentUrl");

                //删除附件文件
                File fileDir = new File(uploadFileDir + attachmentUrl);

                boolean deleteResult = fileDir.delete();

                //删除附件基本信息
                if (deleteResult) {
                    appletCommonMapper.delAnnex((int) map.get("id"));
                }
            }

            return AjaxResult.success();
        }
    }

    /**
     * 自定义时间格式
     *
     * @param timeFormat 格式化
     * @param date       日期
     * @return
     */
    public static String getDate(String timeFormat, Date date) {
        DateFormat dateFormat = new SimpleDateFormat(timeFormat);
        return dateFormat.format(date);
    }


}
